from decimal import Decimal

from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from django_redis import get_redis_connection
# Create your views here.
from goods.models import SKU
from orders.serializers import OrderSerialzier, OrderSaveSerializes


class GetSelectedSKU(APIView):
    """
    获取选中状态的商品
    因为运费统一，不用每一次返回
    {fright:10{count:10
    sku_id : 20}}

    """
    def get(self,request):
    # 获取前端数据
        user = request.user
        # 获取用户
        # 从redis 中获取用户sku_id
        coon = get_redis_connection("cart")
        cart = {}
        sku_id_count = coon.hgetall("cart_%s" % user.id)
        for sku_id ,count in sku_id_count.items():
            cart[int(sku_id)] = int(count)
        # 获取set 中的selected
        selected = coon.smembers("cart_selected_%s" % user.id)
        # 获取商品对象
        skus = SKU.objects.filter(id__in = selected)
        # 给商品对象增加count值
        for sku in skus:
            sku.count = cart[sku.id]
        # 指定运费

        freight = Decimal(10.00)
        # 序列化数据
        ser = OrderSerialzier({"freight":freight,"skus":skus})

        return Response(ser.data)


class OrderSaveView(CreateAPIView):
    """
        保存订单
    """
    permission_classes = [IsAuthenticated]
    serializer_class = OrderSaveSerializes
